package com.cq.hd.order.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONObject;
import cn.hutool.json.XML;
import com.alibaba.fastjson.JSONArray;
import com.cq.hd.common.constant.HfConstant;
import com.cq.hd.member.api.vo.AppUserVo;
import com.cq.hd.order.api.pft.*;
import com.cq.hd.order.config.DynamicCommonConfig;
import com.cq.hd.order.po.TbOrderItemPo;
import com.cq.hd.order.service.PftService;
import com.cq.hd.order.utils.JAXBXmlUtil;
import com.cq.hd.order.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 票付通 服务实现类
 * </p>
 *
 * @author mYunYu
 * @since 2023-12-13
 */
@Slf4j
@Service
public class PftServiceImpl implements PftService {

    @Value("${pft.ac}")
    private String ac;

    @Value("${pft.pw}")
    private String pw;

    @Value("${pft.url}")
    private String url;//景区id：2633 门票id：5715 供应商id：113
    //
    //private String ac="70996337";
    //private String pw="b6a3dc322ff5e462073ce0ace4695779";
    //private String url="http://open.12301.cc/openService/pftMX.php";

    private String md5Str;

    @Autowired
    private RestTemplate restTemplate;

    public boolean checkVerifyCode(String verifyCode) {
        String md5Str = MD5.create().digestHex(ac + pw);
        return md5Str.equals(verifyCode);
    }

    public String getPftResultXml(String result, String methodResponse, String method) {
        JSONObject xmlJSONObj = XML.toJSONObject(result);
        //提取所需部分的xml信息    methodResponse,method表示不同方法的不同xml节点
        return xmlJSONObj.getJSONObject("SOAP-ENV:Envelope").getJSONObject("SOAP-ENV:Body").getJSONObject(methodResponse)
                .getJSONObject(method).get("content").toString();
    }

    private String getPlayTime(String enroolInfo) {
        String playtime = "";
        try {
            if (StrUtil.isNotBlank(enroolInfo)) {
                JSONArray jsonArray = com.alibaba.fastjson.JSONObject.parseArray(enroolInfo);
                for (int i = 0; i < jsonArray.size(); i++) {
                    com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(i);
                    if (jsonObject.getString("title").equals("游玩日期")) {
                        JSONArray options = jsonObject.getJSONArray("activeEnrollInfoOptions");
                        for (int j = 0; j < options.size(); j++) {
                            if (options.getJSONObject(j).getString("checkState").equals("2")) {
                                playtime = options.getJSONObject(j).getString("optionText");
                                break;
                            }
                        }
                        break;
                    }
                }
            }
        } catch (Exception e) {
            log.error("报名信息解析错误" + enroolInfo);
        }
        if (StrUtil.isEmpty(playtime)) {
            playtime = LocalDate.now().toString();
        }
        return playtime;
    }

    @Override
    public Object getScenicSpotList() {
        PftScenicSpotListRequestEntity requestEntity = new PftScenicSpotListRequestEntity();
        PftScenicSpotListBody body = new PftScenicSpotListBody();
        PftScenicSpotListParam param = new PftScenicSpotListParam();
        param.setAc(ac);
        param.setPw(pw);
        param.setN("0");
        param.setM("1");
        body.setParam(param);
        requestEntity.setBody(body);
        String strXml = JAXBXmlUtil.convertToXml(requestEntity);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> formEntity = new HttpEntity<>(strXml, httpHeaders);
        String result = restTemplate.postForObject(url, formEntity, String.class);
        String resultXml = getPftResultXml(result, "ns1:Get_ScenicSpot_ListResponse", "Get_ScenicSpot_List");
        String resultJson = XML.toJSONObject(resultXml).toString();
        PftDataResult dataResult = JSONUtil.jsonToObject(resultJson, PftDataResult.class);
        return dataResult.getData().getRec();
    }

    @Override
    public Object getTicketList() {
        PftTicketListRequestEntity requestEntity = new PftTicketListRequestEntity();
        PftTicketListBody body = new PftTicketListBody();
        PftTicketListParam param = new PftTicketListParam();
        param.setAc(ac);
        param.setPw(pw);
        param.setN("155243");
        param.setM("");
        body.setParam(param);
        requestEntity.setBody(body);
        String strXml = JAXBXmlUtil.convertToXml(requestEntity);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> formEntity = new HttpEntity<>(strXml, httpHeaders);
        String result = restTemplate.postForObject(url, formEntity, String.class);
        String resultXml = getPftResultXml(result, "ns1:Get_Ticket_ListResponse", "Get_Ticket_List");
        String resultJson = XML.toJSONObject(resultXml).toString();
        PftDataResult dataResult = JSONUtil.jsonToObject(resultJson, PftDataResult.class);
        return dataResult.getData().getRec();
    }

    @Override
    public PftOrderSubmitResult orderSubmit(TbOrderItemPo orderItemPo, AppUserVo appUserVo) {
        PftOrderSubmitRequestEntity requestEntity = new PftOrderSubmitRequestEntity();
        PftOrderSubmitBody body = new PftOrderSubmitBody();
        PftOrderSubmitParam param = new PftOrderSubmitParam();
        param.setAc(ac);
        param.setPw(pw);
        param.setM(orderItemPo.getPftSupplier());
        param.setLid(orderItemPo.getPftProduct());
        param.setTid(orderItemPo.getPftTicket());
        param.setTnum("1");
        param.setRemotenum(orderItemPo.getSubOrderNo());
        param.setOrdername(appUserVo.getNickName());
        param.setPlaytime(getPlayTime(orderItemPo.getEnrollInfo()));
        param.setOrdertel(appUserVo.getMobile());
        param.setSmsSend("1");
        param.setPaymode("2");
        param.setOrdermode("0");
        param.setConcatID("0");
        param.setPCode("0");
        Map<String, String> callbackUrl = new HashMap<>();
        callbackUrl.put("callBackUrl", DynamicCommonConfig.DOMAIN_URL + HfConstant.PFT_ORDER_NOTIFY_URL);
        callbackUrl.put("callBackTicketUrl", DynamicCommonConfig.DOMAIN_URL + HfConstant.PFT_TICKET_NOTIFY_URL);
        param.setCallbackUrl(JSONUtil.objectToJson(callbackUrl));
        body.setParam(param);
        requestEntity.setBody(body);
        String strXml = JAXBXmlUtil.convertToXml(requestEntity);
        log.error(strXml);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> formEntity = new HttpEntity<>(strXml, httpHeaders);
        String result = restTemplate.postForObject(url, formEntity, String.class);
        log.error(result);
        String resultXml = getPftResultXml(result, "ns1:PFT_Order_SubmitResponse", "PFT_Order_Submit");
        String resultJson = XML.toJSONObject(resultXml).toString();
        PftDataResult dataResult = JSONUtil.jsonToObject(resultJson, PftDataResult.class);
        return JSONUtil.getPftDataResultRec(dataResult, PftOrderSubmitResult.class);
    }

    @Override
    public PftOrderSubmitResult orderSubmit() {
        PftOrderSubmitRequestEntity requestEntity = new PftOrderSubmitRequestEntity();
        PftOrderSubmitBody body = new PftOrderSubmitBody();
        PftOrderSubmitParam param = new PftOrderSubmitParam();
        param.setAc(ac);
        param.setPw(pw);
        param.setM("35474379");
        param.setLid("2252031");
        param.setTid("454827");
        param.setTnum("1");
        param.setRemotenum("SONO078401707286849858");
        param.setOrdername("特惠票123");
        param.setPlaytime(LocalDate.now().toString());
        param.setOrdertel("15959341626");
        param.setSmsSend("1");
        param.setPaymode("2");
        param.setOrdermode("0");
        param.setConcatID("0");
        param.setPCode("0");
        Map<String, String> callbackUrl = new HashMap<>();
        callbackUrl.put("callBackUrl", DynamicCommonConfig.DOMAIN_URL + HfConstant.PFT_ORDER_NOTIFY_URL);
        callbackUrl.put("callBackTicketUrl", DynamicCommonConfig.DOMAIN_URL + HfConstant.PFT_TICKET_NOTIFY_URL);
        param.setCallbackUrl(JSONUtil.objectToJson(callbackUrl));
        body.setParam(param);
        requestEntity.setBody(body);
        String strXml = JAXBXmlUtil.convertToXml(requestEntity);
        log.error(strXml);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        //httpHeaders.add("all-async-code", "1");
        HttpEntity<String> formEntity = new HttpEntity<>(strXml, httpHeaders);
        String result = restTemplate.postForObject(url, formEntity, String.class);
        log.error(result);
        String resultXml = getPftResultXml(result, "ns1:PFT_Order_SubmitResponse", "PFT_Order_Submit");
        String resultJson = XML.toJSONObject(resultXml).toString();
        PftDataResult dataResult = JSONUtil.jsonToObject(resultJson, PftDataResult.class);
        return JSONUtil.getPftDataResultRec(dataResult, PftOrderSubmitResult.class);
    }

    @Override
    public boolean OrderChangePro(String pftOrder) {
        PftOrderChangeProRequestEntity requestEntity = new PftOrderChangeProRequestEntity();
        PftOrderChangeProBody body = new PftOrderChangeProBody();
        PftOrderChangeProParam param = new PftOrderChangeProParam();
        param.setAc(ac);
        param.setPw(pw);
        param.setOrdern(pftOrder);
        //  0 为取消订单 -1 不做修改，指要修改订单取票人手机
        param.setNum("0");
        body.setParam(param);
        requestEntity.setBody(body);
        String strXml = JAXBXmlUtil.convertToXml(requestEntity);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> formEntity = new HttpEntity<>(strXml, httpHeaders);
        String result = restTemplate.postForObject(url, formEntity, String.class);
        log.error(result);
        String resultXml = getPftResultXml(result, "ns1:Order_Change_ProResponse", "Order_Change_Pro");
        String resultJson = XML.toJSONObject(resultXml).toString();
        PftDataResult dataResult = JSONUtil.jsonToObject(resultJson, PftDataResult.class);
        PftOrderChangeProResult pftOrderChangeProResult = JSONUtil.getPftDataResultRec(dataResult, PftOrderChangeProResult.class);
        return "100".equals(pftOrderChangeProResult.getUudone());
    }

    //查询订单
    @Override
    public OrderQueryDataResult OrderQuery() {
        OrderQueryResultEntity orderQueryResultEntity = new OrderQueryResultEntity();
        OrderQueryBody orderQueryBody = new OrderQueryBody();
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setAc(ac);
        orderQuery.setPw(pw);
        orderQuery.setPftOrdernum("70652899712077");
        orderQueryBody.setOrderQuery(orderQuery);
        orderQueryResultEntity.setBody(orderQueryBody);
        String strXml = JAXBXmlUtil.convertToXml(orderQueryResultEntity);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> formEntity = new HttpEntity<>(strXml, httpHeaders);
        String result = restTemplate.postForObject(url, formEntity, String.class);
        String orderQueryDataResultXml = getPftResultXml(result, "ns1:OrderQueryResponse", "OrderQuery");
        String orderQueryDataResultJson = XML.toJSONObject(orderQueryDataResultXml).toString();
        OrderQueryDataResult orderQueryDataResult = JSONUtil.jsonToObject(orderQueryDataResultJson, OrderQueryDataResult.class);
        return orderQueryDataResult;
    }

    public boolean orderPreCheck(TbOrderItemPo orderItemPo, AppUserVo appUserVo) {
        PftOrderPreCheckRequestEntity orderPreCheckRequestEntity = new PftOrderPreCheckRequestEntity();
        PftOrderPreCheckBody body = new PftOrderPreCheckBody();
        PftOrderPreCheckParam param = new PftOrderPreCheckParam();
        param.setAc(ac);
        param.setPw(pw);
        param.setM(orderItemPo.getPftSupplier());
        param.setTid(orderItemPo.getPftTicket());
        param.setTnum("1");
        param.setOrdername(appUserVo.getNickName());
        param.setPlaytime(getPlayTime(orderItemPo.getEnrollInfo()));
        param.setOrdertel(appUserVo.getMobile());
        param.setTnum("1");
        param.setPaymode("2");
        body.setParam(param);
        orderPreCheckRequestEntity.setBody(body);

        String strXml = JAXBXmlUtil.convertToXml(orderPreCheckRequestEntity);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> formEntity = new HttpEntity<>(strXml, httpHeaders);
        String result = restTemplate.postForObject(url, formEntity, String.class);
        String resultXml = getPftResultXml(result, "ns1:OrderPreCheckResponse", "OrderPreCheck");
        String resultJson = XML.toJSONObject(resultXml).toString();
        PftDataResult dataResult = JSONUtil.jsonToObject(resultJson, PftDataResult.class);
        PftOrderPreCheckResult orderPreCheckResult = JSONUtil.getPftDataResultRec(dataResult, PftOrderPreCheckResult.class);
        if ("100".equals(orderPreCheckResult.getUudone())) {
            return true;
        }
        log.error(strXml);
        log.error(resultJson);
        return false;
    }

    //预判下单
    public boolean orderPreCheck(String pftSupplier, String pftProduct, String pftTicket) {
        PftOrderPreCheckRequestEntity orderPreCheckRequestEntity = new PftOrderPreCheckRequestEntity();
        PftOrderPreCheckBody body = new PftOrderPreCheckBody();
        PftOrderPreCheckParam param = new PftOrderPreCheckParam();
        param.setAc(ac);
        param.setPw(pw);
        param.setTid(pftTicket);
        param.setTnum("1");
        LocalDate now = LocalDate.now();
        param.setPlaytime(now.toString());
        param.setOrdertel("15959341626");
        param.setOrdername("预判订单");
        param.setM(pftSupplier);
        param.setPaymode("2");
        body.setParam(param);
        orderPreCheckRequestEntity.setBody(body);

        String strXml = JAXBXmlUtil.convertToXml(orderPreCheckRequestEntity);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> formEntity = new HttpEntity<>(strXml, httpHeaders);
        String result = restTemplate.postForObject(url, formEntity, String.class);
        String resultXml = getPftResultXml(result, "ns1:OrderPreCheckResponse", "OrderPreCheck");
        String resultJson = XML.toJSONObject(resultXml).toString();
        PftDataResult dataResult = JSONUtil.jsonToObject(resultJson, PftDataResult.class);
        PftOrderPreCheckResult orderPreCheckResult = JSONUtil.getPftDataResultRec(dataResult, PftOrderPreCheckResult.class);
        if ("100".equals(orderPreCheckResult.getUudone())) {
            return true;
        }
        return false;
    }

}
